#! /usr/bin/python
# coding=utf-8

import urllib
import urllib2
import multiprocessing
import time
import json
import os
import sys
import redis

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config.tdm_config import *

reload(sys)
sys.setdefaultencoding('utf-8')

DEBUG = True
server_sleep = 300
server_delay = 0.1

#posturl = "http://101.36.75.5:8102/recv/network"
posturl = "http://127.0.0.1:8102/recv/network"

def multiproc_network_ping(city, jxd, device, ip):
    ret_network_ping = {}

    cmd = 'ping -c 3 -n -w 3 %s > /dev/null 2>&1' % (ip,)

    if DEBUG:
        print cmd

    ret = os.system(cmd)
    key = '%s:%s:%s:%s' % (city, jxd, device, tdm_redis_key_network_online_suffix)

    if ret == 0:
        ret_network_ping[key] = 1
    else:
        ret_network_ping[key] = -1

    if DEBUG:
        print key, ret_network_ping[key]

    return ret_network_ping

def read_ip_addr_from_redis():
    r = redis.Redis(host='127.0.0.1', db=1)
    net_dev_list = []
    for city_jxd_dev, netdev_attr in r.hgetall(tdm_redis_key_network).items():
        city, jxd, dev = city_jxd_dev.split(':')
        netdev_dict = json.loads(netdev_attr)
        net_dev = {}
        net_dev['city'] = city
        net_dev['jxd'] = jxd
        net_dev['device'] = dev
        net_dev['ip'] = netdev_dict.get('ipaddr', '')
        '''
        if not (city == '北京' and jxd == '综合楼' and dev == '路由'):    #北京_综合楼_路由
            continue
        '''
        net_dev_list.append(net_dev)
    return net_dev_list

def network_post(url, data):
    data = urllib.urlencode(data)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req, timeout=5)
    return response.read()

def network_multiple_ping():
    ping_post_dict = {}
    dev_list = read_ip_addr_from_redis()

    pool = multiprocessing.Pool(processes=100)
    result = []
    for dev in dev_list:
        result.append(pool.apply_async(multiproc_network_ping, (dev.get('city'), dev.get('jxd'), dev.get('device'), dev.get('ip'))))

    pool.close()
    pool.join()

    for ret in result:
        ret_dict = ret.get()
        if DEBUG:
            print ret_dict
        ping_post_dict.update(ret_dict)

    network_post(posturl, ping_post_dict)

if __name__ == "__main__":
    network_multiple_ping()
